using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace LiJ.Pay.WeiXin.SysTools
{
	internal static class SysUtil
	{
		private static readonly Random _rnd = new Random();

		private static readonly char[] _arrChar = new char[60]
		{
			'0',
			'1',
			'2',
			'3',
			'4',
			'5',
			'6',
			'7',
			'8',
			'9',
			'a',
			'b',
			'd',
			'c',
			'e',
			'f',
			'g',
			'h',
			'i',
			'j',
			'k',
			'l',
			'm',
			'n',
			'p',
			'r',
			'q',
			's',
			't',
			'u',
			'v',
			'w',
			'z',
			'y',
			'x',
			'A',
			'B',
			'C',
			'D',
			'E',
			'F',
			'G',
			'H',
			'I',
			'J',
			'K',
			'L',
			'M',
			'N',
			'Q',
			'P',
			'R',
			'T',
			'S',
			'V',
			'U',
			'W',
			'X',
			'Y',
			'Z'
		};

		/// <summary>
		///  字典转到xml
		/// </summary>
		/// <param name="dics"></param>
		/// <returns></returns>
		public static string ProduceXml(this SortedDictionary<string, object> dics)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<xml>");
			foreach (KeyValuePair<string, object> dic in dics)
			{
				object value = dic.Value;
				string value2 = (value != null) ? value.ToString() : null;
				if (!string.IsNullOrEmpty(value2))
				{
					if (dic.Value is int || dic.Value is long || dic.Value is double || dic.Value is float)
					{
						stringBuilder.Append("<").Append(dic.Key).Append(">")
							.Append(value2)
							.Append("</")
							.Append(dic.Key)
							.Append(">");
					}
					else
					{
						stringBuilder.Append("<").Append(dic.Key).Append(">")
							.Append("<![CDATA[")
							.Append(value2)
							.Append("]]>")
							.Append("</")
							.Append(dic.Key)
							.Append(">");
					}
				}
			}
			stringBuilder.Append("</xml>");
			return stringBuilder.ToString();
		}

		/// <summary>
		/// 把xml文本转化成字典对象
		/// </summary>
		/// <param name="xmlStr"></param>
		/// <param name="xmlDoc">通过字符串转化后的xml对象</param>
		/// <returns></returns>
		public static SortedDictionary<string, object> ChangXmlToDir(string xmlStr, ref XmlDocument xmlDoc)
		{
			if (string.IsNullOrEmpty(xmlStr))
			{
				return null;
			}
			SortedDictionary<string, object> sortedDictionary = new SortedDictionary<string, object>();
			xmlDoc = new XmlDocument();
			xmlDoc.LoadXml(xmlStr);
			foreach (XmlNode childNode in xmlDoc.FirstChild.ChildNodes)
			{
				sortedDictionary[childNode.Name] = childNode.InnerText;
			}
			return sortedDictionary;
		}

		/// <summary>
		/// 生成随机串
		/// </summary>
		/// <returns></returns>
		public static string GenerateNonceStr()
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < 8; i++)
			{
				stringBuilder.Append(SysUtil._arrChar[SysUtil._rnd.Next(0, 59)].ToString());
			}
			return stringBuilder.ToString();
		}
	}
}
